<template>
  <div class="login h-full flex justify-center items-center">
    <a-form
      ref="formRef"
      :model="formState"
      :rules="rules"
      label-width=""
      class="login-container"
    >
      <h3 class="text-center">系统登录</h3>
      <a-form-item name="userName">
        <a-input
          type="text"
          :placeholder="'请输入用户名'"
          prefix-icon="el-icon-user"
          v-model:value="formState.userName"
          clearable
        >
        </a-input>
      </a-form-item>
      <a-form-item name="password">
        <a-input
          type="password"
          :placeholder="'请输入密码'"
          prefix-icon="el-icon-lock"
          v-model:value="formState.password"
          show-password
        >
        </a-input>
      </a-form-item>
      <a-form-item>
        <a-button
          class="w-full"
          type="primary"
          :loading="loading"
          @click="onSubmit"
        >
          登陆
        </a-button>
      </a-form-item>
    </a-form>
  </div>
</template>

<script setup>
import { ref, reactive } from "vue";
import { useRouter } from "vue-router";
import { useStore } from "@/store/index";

const formRef = ref();
const store = useStore();
const router = useRouter();
const loading = ref(false);
const formState = reactive({
  userName: "admin",
  password: "123456",
});

const rules = {
  userName: [
    { required: true, message: "请输入用户名", trigger: "blur" },
    { min: 3, max: 10, message: "长度在 3 到 10 个字符", trigger: "blur" },
  ],
  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { min: 6, max: 12, message: "长度在 6 到 12 个字符", trigger: "blur" },
  ],
};

const onSubmit = async () => {
  formRef.value
    .validate()
    .then(async () => {
      // 开启 loading
      loading.value = true;
      // 登陆
      const res = await store.dispatch("user/login", formState);
      if (res) {
        const path = router.currentRoute.value.query.redirect || "/";
        router.push(path);
      }
      // 关闭 loading
      loading.value = false;
    })
    .catch((error) => {
      console.log("error", error);
      // 关闭 loading
      loading.value = false;
    });
};
</script>

<style lang="scss" scoped>
.login {
  background: url("@/assets/images/bg_login.jpg") no-repeat;
  background-position: center;
  height: 100%;
  width: 100%;
  background-size: cover;
  position: fixed;
  .login-container {
    border-radius: 15px;
    background-clip: padding-box;
    width: 350px;
    padding: 15px 35px;
    background: #fff;
    border: 1px solid #eaeaea;
    box-shadow: 0 0 25px #cac6c6;
  }
}
</style>
